package cn.ld.fj.web.order;

import cn.ld.fj.entity.*;
import cn.ld.fj.entity.account.User;
import cn.ld.fj.pojo.MealOrderFoodPojo;
import cn.ld.fj.service.account.AccountManager;
import cn.ld.fj.service.desk.DeskShopManager;
import cn.ld.fj.service.food.FoodManager;
import cn.ld.fj.service.log.OperationLogManager;
import cn.ld.fj.service.order.ConsumeRecordManager;
import cn.ld.fj.service.order.MealOrderFoodManager;
import cn.ld.fj.service.order.MealOrderManager;
import cn.ld.fj.service.vip.VipUserManager;
import cn.ld.fj.util.DwzUtil;
import cn.ld.fj.web.JsonActionSupport;
import com.google.common.collect.Lists;
import net.esoar.modules.orm.Page;
import net.esoar.modules.orm.PropertyFilter;
import net.esoar.modules.utils.web.struts2.Struts2Utils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

/**
 * 用户管理Action.
 * <p/>
 * 使用Struts2 convention-plugin annotation定义Action参数. 演示带分页的管理界面.
 *
 * @author fly
 */
@Namespace("/order")
// 定义名为reload的result重定向到user.action, 其他result则按照convention默认.
@Results({@Result(name = JsonActionSupport.RELOAD, location = "meal-order.action", type = "redirect")})
public class MealOrderAction extends JsonActionSupport<MealOrder> {

    private final Logger logger = LoggerFactory.getLogger(MealOrderAction.class);


    @Autowired
    private MealOrderManager mealOrderManager;
    @Autowired
    private DeskShopManager deskShopManager;
    @Autowired
    private AccountManager accountManager;
    @Autowired
    private MealOrderFoodManager mealOrderFoodManager;
    @Autowired
    private FoodManager foodManager;
    @Autowired
    private OperationLogManager operationLogManager;
    @Autowired
    private VipUserManager vipUserManager;
    @Autowired
    private ConsumeRecordManager consumeRecordManager;


    private String cardNo;
    private float realMoney;
    private int payType;


    private Long id;
    private MealOrder entity;
    private Page<MealOrder> page = new Page<MealOrder>(10);// 每页5条记录

    private int type;

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    private List<DeskShop> deskShops = Lists.newArrayList();

    private List<MealOrderFoodPojo> mealOrderFoodPojos = Lists.newArrayList();


    public String getCardNo() {
        return cardNo;
    }

    public void setCardNo(String cardNo) {
        this.cardNo = cardNo;
    }

    public float getRealMoney() {
        return realMoney;
    }

    public void setRealMoney(float realMoney) {
        this.realMoney = realMoney;
    }

    public int getPayType() {
        return payType;
    }

    public void setPayType(int payType) {
        this.payType = payType;
    }

    public List<MealOrderFoodPojo> getMealOrderFoodPojos() {
        return mealOrderFoodPojos;
    }

    public void setMealOrderFoodPojos(List<MealOrderFoodPojo> mealOrderFoodPojos) {
        this.mealOrderFoodPojos = mealOrderFoodPojos;
    }

    public List<DeskShop> getDeskShops() {
        return deskShops;
    }

    public void setDeskShops(List<DeskShop> deskShops) {
        this.deskShops = deskShops;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public MealOrder getModel() {
        return entity;
    }


    public Long getId() {
        return id;
    }

    public MealOrder getEntity() {
        return entity;
    }

    public void setEntity(MealOrder entity) {
        this.entity = entity;
    }

    public Page<MealOrder> getPage() {
        return page;
    }

    public void setPage(Page<MealOrder> page) {
        this.page = page;
    }

    @Override
    protected void prepareModel() throws Exception {
        if (id != null) {
            entity = mealOrderManager.getOne(id);
        } else {
            entity = new MealOrder();
        }
    }

    // -- CRUD Action 函数 --//
    @Override
    public String list() throws Exception {
        List<PropertyFilter> filters = PropertyFilter
                .buildFromHttpRequest(Struts2Utils.getRequest());
        // 设置默认排序方式
        if (!page.isOrderBySetted()) {
            page.setOrderBy("id");
            page.setOrder(Page.ASC);
        }

        page = mealOrderManager.getPage(page, filters);
        if (CollectionUtils.isNotEmpty(page.getResult())) {
            for (MealOrder mealOrder : page.getResult()) {
                DeskShop deskShop = deskShopManager.getOne(mealOrder.getDeskShopId());
                if (deskShop != null) {
                    mealOrder.setDeskNum(deskShop.getDnumber());
                }

                User user = accountManager.getUser(mealOrder.getUserId());
                if (user != null) {
                    mealOrder.setUserName(user.getName());
                }
            }
        }

        if (type == 1) {
            return "hc";
        }
        return SUCCESS;
    }

    @Override
    public String input() throws Exception {
        deskShops = deskShopManager.findAll();
        return INPUT;
    }


    public String jz() throws Exception {
        prepareModel();
        deskShops = deskShopManager.findAll();


        return "jz";
    }


    public void getMealOrderPojos(Long id) {
        List<MealOrderFood> mealOrderFoods = mealOrderFoodManager.findListFood(id);
        if (CollectionUtils.isNotEmpty(mealOrderFoods)) {
            for (MealOrderFood mealOrderFood : mealOrderFoods) {
                MealOrderFoodPojo mealOrderFoodPojo = new MealOrderFoodPojo();
                BeanUtils.copyProperties(mealOrderFood, mealOrderFoodPojo);

                Food food = foodManager.getOne(mealOrderFood.getFoodId());
                if (food != null) {
                    mealOrderFoodPojo.setFoodName(food.getFoodName());
                }

                mealOrderFoodPojos.add(mealOrderFoodPojo);
            }
        }
    }


    public String viewMealFood() throws Exception {
        getMealOrderPojos(id);
        return "food";
    }


    @Override
    public void save() throws Exception {

        mealOrderManager.save(entity);
        operationLogManager.saveLog("修改订单信息");

        Struts2Utils.renderHtml(DwzUtil.getCloseCurrentReturn("w_meal_order",
                "操作成功"));
    }


    public void jzSub() throws Exception {

        MealOrder mealOrder = mealOrderManager.getOne(id);
        if (mealOrder != null && mealOrder.getOrderType() == 2) {
            Struts2Utils.renderHtml(DwzUtil.getFailReturn("该订单已经结账,无需重复结账"));
            return;
        }

        if (payType == 4) {
            VipUser vipUser = vipUserManager.getOneByCardNum(cardNo);
            if (vipUser == null) {
                Struts2Utils.renderHtml(DwzUtil.getFailReturn("卡号不存在"));
                return;
            }
            if (vipUser.getBalance() < realMoney) {
                Struts2Utils.renderHtml(DwzUtil.getFailReturn("卡余额不足,请充值"));
                return;
            }
            vipUser.setBalance(vipUser.getBalance() - realMoney);
            ConsumeRecord consumeRecord = new ConsumeRecord();
            consumeRecord.setCreateDate(new Date());
            consumeRecord.setCardNo(cardNo);
            consumeRecord.setOrderId(mealOrder.getId());
            consumeRecord.setMoney(realMoney);
            consumeRecordManager.save(consumeRecord);

        }

        mealOrder.setOrderType(2);
        mealOrder.setPayType(payType);
        mealOrder.setRealMoney(realMoney);

        mealOrderManager.save(mealOrder);

        Struts2Utils.renderHtml(DwzUtil.getCloseCurrentReturn("w_meal_order",
                "操作成功"));
    }


    @Override
    public void delete() throws Exception {


        try {
            mealOrderManager.delete(id);
            operationLogManager.saveLog("删除订单");

        } catch (Exception e) {
            return;
        }

        Struts2Utils.renderHtml(DwzUtil.getNavtabReturn("w_meal_order",
                "操作成功"));
    }


}
